package com.meida.student.app.user.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.interceptor.UpdateInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.OrderNoUtil;
import com.meida.common.utils.RedisUtils;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusSubject;
import com.meida.module.bus.client.entity.BusTutorType;
import com.meida.module.bus.client.enums.OrderStateZEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.client.enums.PayStateEnum;
import com.meida.module.bus.client.enums.TutorChargeTypeEnum;
import com.meida.module.bus.provider.service.BusSubjectService;
import com.meida.module.bus.provider.service.BusTutorTypeService;
import com.meida.module.bus.provider.utils.MyDateUtils;
import com.meida.module.file.provider.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 用户更新订单
 */
@Slf4j
@Component
public class UpdateOrderHandler implements UpdateInterceptor<BusOrder> {

    @Autowired
    private OrderNoUtil orderNoUtil;


    @Autowired
    private BusTutorTypeService busTutorTypeService;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private BusSubjectService busSubjectService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public ResultBody validate(CriteriaUpdate cs, EntityMap params) {
        //订单类型(1:拍照,2:预约,3:作业无忧)
        Integer orderType = params.getInt("orderType");
        Long subjectId = params.getLong("subjectId");
        String subjectIds = params.get("subjectIds");
        String orderDescribe = params.get("orderDescribe");
        //附件Ids
        String fileIds = params.get("fileIds");
        ApiAssert.allNotNull("缺少订单参数", orderType, subjectId, subjectIds, orderDescribe);
        if (orderType.equals(OrderTypeEnum.TakePhotosAskQuestions.getValue())) {
            ApiAssert.allNotNull("请上传图片", fileIds);
        } else {
            ApiAssert.allNotNull("请上传图片或者附件", fileIds);
        }
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaUpdate criteriaUpdate, EntityMap entityMap, BusOrder busOrder) {
        Integer orderType = entityMap.getInt("orderType");
        //是否保存草稿
        Integer tag = entityMap.getInt("tag", 0);
        if (!tag.equals(2)) {
            //指定学霸下单
            Long answerUserId = entityMap.getLong("answerUserId");
            //悬赏金额
            BigDecimal rewardAmount = entityMap.getBigDecimal("rewardAmount");
            busOrder.setRewardAmount(rewardAmount);
            Long subjectId = entityMap.getLong("subjectId");
            if (OrderTypeEnum.TakePhotosAskQuestions.getValue() == orderType) {
                //根据subjectId计算订单金额
                BusSubject busSubject = busSubjectService.getById(subjectId);
                BigDecimal amount = busSubject.getAmount();
                busOrder.setOrderAmount(amount);
            }
            if (OrderTypeEnum.BookingTutoring.getValue() == orderType) {
                //根据辅导类型去计算订单金额
                //辅导类型
                Long tutorTypeId = entityMap.getLong("tutorTypeId");
                ApiAssert.isNotEmpty("tutorTypeId不能为空", tutorTypeId);
                BusTutorType tutorType = busTutorTypeService.getById(tutorTypeId);
                ApiAssert.isNotEmpty("辅导类型不存在", tutorType);
                Integer chargeType = tutorType.getChargeType();
                //辅导单价
                BigDecimal tutorPrice = tutorType.getTutorPrice();
                //订单金额
                BigDecimal orderAmount;
                //预约时间
                String appointmentDate = entityMap.get("appointmentDate");
                String appointmentTime = entityMap.get("appointmentTime");
                ApiAssert.allNotNull("缺少预约辅导订单参数", appointmentDate, appointmentTime);
                if (chargeType.equals(TutorChargeTypeEnum.Time.getValue())) {
                    //预约时长
                    BigDecimal durationTime = entityMap.getBigDecimal("durationTime");
                    ApiAssert.allNotNull("缺少预约辅导订单参数", durationTime);
                    orderAmount = tutorPrice.multiply(durationTime);

                } else {
                    //按次时即为订单金额
                    orderAmount = tutorPrice;
                }
                String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
                Date expireTime = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
                String targetTimezone = httpServletRequest.getHeader("targetTimezone");
                Date newDate = MyDateUtils.convertTimezone(expireTime, targetTimezone, "UTC");
                String newAppointmentDateStr = DateUtils.formatDate(newDate, "yyyy-MM-dd");
                String newAppointmentTimeStr = DateUtils.formatDate(newDate, "HH:mm");
                busOrder.setAppointmentDate(newAppointmentDateStr);
                busOrder.setAppointmentTime(newAppointmentTimeStr);
                busOrder.setOrderAmount(orderAmount);
            }
            if (OrderTypeEnum.HomeWork.getValue().equals(orderType)) {
                //作业无忧类型计算订单金额
                //截止日期
                String appointmentDate = entityMap.get("appointmentDate");
                String appointmentTime = entityMap.get("appointmentTime");
                BigDecimal expectedAmount = entityMap.getBigDecimal("expectedAmount");
                ApiAssert.allNotNull("缺少作业无忧订单参数", rewardAmount, appointmentDate, expectedAmount);
                //最低报价金额
                BusSubject busSubject = busSubjectService.getById(subjectId);
                BigDecimal minAmount = busSubject.getAmount();
                if (FlymeUtils.lt(minAmount, rewardAmount)) {
                    ApiAssert.failure("预期报价不能低于" + minAmount);
                }
                busOrder.setOrderAmount(BigDecimal.ZERO);
                if (FlymeUtils.isNotEmpty(answerUserId)) {
                    busOrder.setOrderAmount(expectedAmount);
                }
                //作业无忧默认待出价状态
                busOrder.setOrderState(OrderStateZEnum.OrderState1.getValue());
                String appointmentDateTimeStr = appointmentDate + " " + appointmentTime + ":00";
                Date expireTime = DateUtils.strToDate(appointmentDateTimeStr, "yyyy-MM-dd HH:mm:ss");
                String targetTimezone = httpServletRequest.getHeader("targetTimezone");
                Date newDate = MyDateUtils.convertTimezone(expireTime, targetTimezone, "UTC");
                String newAppointmentDateStr = DateUtils.formatDate(newDate, "yyyy-MM-dd");
                String newAppointmentTimeStr = DateUtils.formatDate(newDate, "HH:mm");
                busOrder.setAppointmentDate(newAppointmentDateStr);
                busOrder.setAppointmentTime(newAppointmentTimeStr);
                busOrder.setExpiryTime(newAppointmentDateStr + " " + newAppointmentTimeStr);
            } else {
                //除作业无忧外，未支付的订单都默认-1（草稿箱查询-1）
                busOrder.setOrderState("-1");
            }
            if (tag.equals(1)) {
                //保存草稿箱
                busOrder.setOrderState("-1");
            }
            busOrder.setRewardAmount(rewardAmount);
            //全局配置
            EntityMap config = redisUtils.getConfigMap("SERVICE_FEE_CONFIG");
            //佣金比例
            BigDecimal platformServiceFee = config.getBigDecimal("platformServiceFee");
            BigDecimal commissionRate = new BigDecimal(0.2);
            if (FlymeUtils.isNotEmpty(platformServiceFee)) {
                commissionRate = platformServiceFee.divide(new BigDecimal(100));
            }
            BigDecimal orderAmount = busOrder.getOrderAmount();
            //计算佣金金额(订单金额+悬赏金额)*(1-佣金比例)
            BigDecimal commission = orderAmount.add(rewardAmount).multiply(BigDecimal.ONE.subtract(commissionRate));
            busOrder.setCommission(commission);
            //设置支付状态
            busOrder.setPayState(PayStateEnum.NoPay.getValue());
            busOrder.setPayableAmount(orderAmount.add(rewardAmount));
        }
        //设置封面图,从附件中取图片类型
        String fileIds = entityMap.get("fileIds");
        String coverImg = sysFileService.getCoverImg(fileIds);
        busOrder.setCoverImg(coverImg);

    }

}
